
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>


#include "account_mutex.h"

// 创建账户
extern Account *create_account(int code, double balance)
{
    assert(balance >= 0.0);
    Account *account = (Account *)malloc(sizeof(Account));
    assert(account != NULL);

    account->code = code;
    account->balance = balance;
    pthread_mutex_init(&account->mutex, NULL);

    return account;
}

// 销毁账户
extern void destroy_account(Account *a)
{
}

// 取款
extern double withdraw(Account *a, double amt)
{
    assert(a != NULL);

    pthread_mutex_lock(&a->mutex);
    if (amt < 0.0 || amt > a->balance)
    {
        pthread_mutex_unlock(&a->mutex);
        return 0.0;
    }

    //模拟实际银行取钱业务，从远程数据库获取数据，暂存，修改后同步到远程数据库
    double balance = a->balance;
    sleep(1);
    balance -= amt;
    a->balance = balance;

    pthread_mutex_unlock(&a->mutex);
    return amt;
}

// 存款
extern double deposit(Account *a, double amt)
{
    double balance = 0.0;

    return balance;
}

// 查询账户余额
extern double get_balance(Account *a, double amt)
{
    double balance = 0.0;

    return balance;
}
